Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
How to set first value in "useState" function to true or false with "useEffect" function React

I am running into a problem with my current code. The code below is supposed to grab a JSON response from my backend and set "data" in the useState function to true or false based on the backend's response. The issue I am having is that when I click on my button to redirect me to the page it must first go through this protected route in my react router. So it will run this script but the value of 'data' never changes. However, my console.log will output the correct boolean based on the JSON response sent from the backend. I am confused on how I can actually grab my JSON response on page load and set it to 'data' with useEffect? From my understanding, useEffect will only update my useState 'data' when the DOM re-renders.

In short, I want data to = true on page render by checking the JSON response from my backend using axios and if it is true I want to be redirected to the outlet.

I appreciate any help thanks.

 const useAuth = () => {
    
      const [data, setData] = useState(false);
    
      useEffect(() => {
        const fetchAuthData = async () => {
          await axios.get('http://localhost:5000/auth')
            .then(resp => {
              console.log(resp.data)
              setData(resp.data);
            })
            .catch(err => {
              console.log(err);
              setData(false)
            });
    
    
        };
    
        fetchAuthData()
      }, []);
    
      console.log(data)
      // Logic to check if backEndResponse is true or false
      if (data === true) {
        const authorized = { loggedIn: true }
        return authorized && authorized.loggedIn;
      } else {
        const authorized = { loggedIn: false }
        return authorized && authorized.loggedIn;
      }
    
    };
    
    
    const ProtectedRoutes = () => {
      const isAuth = useAuth();
      return isAuth ? <Outlet/> : <Navigate to="/login" />;
    }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Ok, from what I can understand of your question, the issue is that the ProtectedRoutes layout component is using the initial data state, which is false, and handling the auth redirect before the actual auth GET request is fully processed.

You should use a third "indeterminant" state to hold off on rendering the Outlet or redirect until the auth status is confirmed.

Example:

const useAuth = () => {
  const [data, setData] = useState(); // <-- initially undefined

  useEffect(() => {
    const fetchAuthData = async () => {
      await axios.get('http://localhost:5000/auth')
        .then(resp => {
          setData(!!resp.data);
        })
        .catch(err => {
          console.log(err);
          setData(false)
        });
    };

    fetchAuthData()
  }, []);

  return data;
};

...

const ProtectedRoutes = () => {
  const isAuth = useAuth();

  if (isAuth === undefined) return null; // or loading indicator, etc...

  return isAuth ? <Outlet/> : <Navigate to="/login" replace />;
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda